﻿using CRM.Models;
using CRM.Services;
using System.Linq;
using CRM.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using CRM.Enums;
using CRM.ViewModels.User;
using System.Transactions;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace CRM.Controllers.UserManage
{
    using UserModel = Models.User;
    [Route("api/[controller]")]
    [ApiController]
    public class UserCompanyController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> userManager;
        private readonly UserService _UserService;
        private readonly CompanyService _CompanyService;

        public UserCompanyController(MyDbContext dbContext, UserManager<User> userManager, UserService userService, CompanyService companyService)
        {
            _dbContext = dbContext;
            this.userManager = userManager;
            _UserService = userService;
            _CompanyService = companyService;
        }


        /// <summary>
        /// 获取公司用户列表条件信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("[action]")]
        public ResultStruct GetCompanySearchList()
        {
            var u = userManager.GetUserAsync(User).Result;
            var rule = new
            {
                add = true,
                edit = true,
                del = true,
            };

            Company CompanyInfo = _CompanyService.GetInfo(u.CompanyId);
            int Num = _UserService.GetUserNum(u.Id, u.CompanyId, u.OemId);

            var CompanyConfig = new
            {
                IsOpenUser = CompanyInfo.IsOpenUser,
                OpenUserNum = CompanyInfo.OpenUserNum - Num
            };

            RuleTemplateService RuleTemplateService = new(_dbContext);
            var RuleTemplates = RuleTemplateService.GetAllRuleTemplate(u.CompanyId, u.OemId);
            var ResultsRuleTemplates = new Dictionary<int, RuleTemplateService.ChooseData>();
            ResultsRuleTemplates = RuleTemplates.ToDictionary(k => k.Id);

            OemService OemService = new(_dbContext);
            var Oems = OemService.GetOwnOems(u);
            var ResultsOems = new Dictionary<int, OemService.ChooseData>();
            ResultsOems = Oems.ToDictionary(k => k.Id);

            var data = new
            {
                ruleTemplates = ResultsRuleTemplates,
                rule = rule,
                isSysAdmin = (u.Type == UserModel.Types.Super || u.Type == UserModel.Types.Admin) ? true : false, //管理员或超管 true 公司管理员false
                oems = ResultsOems,
                companyConfig = CompanyConfig
            };
            return Success(data);
        }


        /// <summary>
        /// 公司用户列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<ResultStruct> GetCompanyList([FromQuery] GetCompanyList RequestData)
        {
            CompanyUserData UserData = null;
            var UserList = new Dictionary<int, CompanyUserData>();
            int CompanyId = 0;

            var u = userManager.GetUserAsync(User).Result;

            //用户名搜索，先搜索用户信息
            if (!string.IsNullOrEmpty(RequestData.Name))
            {
                UserData = _dbContext.Users.Where(i => i.Type == Models.User.Types.CompanyAdmin)
                    .Where(i => i.Pid == u.Id)
                    .Where(i => i.HashCode == Helper.GetDeterministicHashCode(RequestData.Name)).Select(n =>
                        new CompanyUserData()
                        {
                            Id = n.Id,
                            UserName = n.UserName,
                            TrueName = n.TrueName,
                            CompanyId = n.CompanyId
                        }).FirstOrDefault();
                //无用户 直接让返回
                if (UserData == null)
                {
                    var DataEmpty = new
                    {
                        CompanyData = new
                        {
                            Total = 0,
                            CurrentPage = 1,
                            PageSize = 1,
                            Items = new int[] { }
                        },
                        UserList = UserList
                    };
                    return Success(DataEmpty);
                }

                UserList[UserData.CompanyId] = UserData;
                CompanyId = UserData.CompanyId;
            }

            IQueryable<Company> sqlQuery = _dbContext.Company.Where(i => i.ParentCompanyId == u.CompanyId);

            if (CompanyId != 0)
            {
                sqlQuery = sqlQuery.Where(i => i.Id == CompanyId);
            }

            if (RequestData.State != States.None)
            {
                sqlQuery = sqlQuery.Where(i => i.State == RequestData.State);
            }

            if (RequestData.RuleId != -1)
            {
                sqlQuery = sqlQuery.Where(i => i.RuleId == RequestData.RuleId);
            }

            if (RequestData.OemId != -1)
            {
                sqlQuery = sqlQuery.Where(i => i.ShowOemId == RequestData.OemId);
            }

            if (!string.IsNullOrEmpty(RequestData.ValidityStart))
            {
                long ValidityStart = Helper.GetTimeStamp(Convert.ToDateTime(RequestData.ValidityStart));
                long ValidityEnd = Helper.GetTimeStamp(Convert.ToDateTime(RequestData.ValidityEnd));

                sqlQuery = sqlQuery.Where(i => i.ShowValidity >= ValidityStart);
                sqlQuery = sqlQuery.Where(i => i.ShowValidity <= ValidityEnd);
            }

            //公司信息分页数据
            var CompanyData = await sqlQuery.Select(n =>
                new CompanyListData()
                {
                    Id = n.Id,
                    Name = n.Name,
                    RuleId = n.RuleId,
                    State = n.State,
                    Validity = Helper.TimeStampToDate(n.ShowValidity),
                    OemId = n.ShowOemId,
                    CreatedAt = n.CreatedAt
                }).OrderBy(i => i.State).OrderByDescending(i => i.Id).ToPaginateAsync(Request);


            //取出对应公司下管理员账号信息
            if (UserData == null)
            {
                var CompanyIds = CompanyData.Items.Select(m => m.Id);
                var UserDataList = _dbContext.Users.Where(i => i.Type == Models.User.Types.CompanyAdmin).Where(i => i.Pid == u.Id).Where(m => CompanyIds.Contains(m.CompanyId)).Select(n =>
                    new CompanyUserData()
                    {
                        Id = n.Id,
                        UserName = n.UserName,
                        TrueName = n.TrueName,
                        CompanyId = n.CompanyId
                    }).ToList();

                UserList = UserDataList.ToDictionary(k => k.CompanyId);
            }

            var data = new
            {
                CompanyData = CompanyData,
                UserList = UserList
            };
            return Success(data);
        }


        /// <summary>
        /// 获取添加公司管理员限制信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ResultStruct GetAddLimit()
        {
            var u = userManager.GetUserAsync(User).Result;

            //有效期最大日期
            string LimitValidity = DateTime.Today.AddYears(10).ToString("yyyy-MM-dd");
            var IsOpenUser = Company.IsOpenUsers.ENABLE;
            var IsUnlimitedPoints = Company.IsUnlimitedPointEnum.ENABLE;
            int OpenUserNum = 0;
            int NumberOfPoints = 0;

            Company CompanyInfo = _CompanyService.GetInfo(u.CompanyId);

            if (!(u.CompanyId == 1))
            {
                IsOpenUser = CompanyInfo.IsOpenUser;
                OpenUserNum = CompanyInfo.OpenUserNum;
                IsUnlimitedPoints = CompanyInfo.IsUnlimitedPoints;
                NumberOfPoints = CompanyInfo.NumberOfPoints;

                ValidityService ValidityService = new(_dbContext);
                Validity ValidityInfo = ValidityService.GetMaxValidity(CompanyInfo.ValidityIds);
                LimitValidity = Helper.TimeStampToDate(ValidityInfo.validity);
            }

            RuleTemplateService RuleTemplateService = new(_dbContext);
            var RuleTemplates = RuleTemplateService.GetAllRuleTemplate(u.CompanyId, u.OemId);

            OemService OemService = new(_dbContext);
            var Oems = OemService.GetOwnOems(u);
            //已使用的数量
            int num = _UserService.GetUserNum(u.Id, u.CompanyId, u.OemId);
            var data = new
            {
                RuleTemplates = RuleTemplates,
                LimitValidity = LimitValidity,
                IsOpenUser = IsOpenUser,
                OpenUserNum = OpenUserNum - num,
                IsUnlimitedPoints = IsUnlimitedPoints,
                NumberOfPoints = NumberOfPoints,
                Oems = Oems,
                OemId = u.OemId,
                isSysAdmin = (u.Type == UserModel.Types.Super || u.Type == UserModel.Types.Admin) ? true : false, //管理员或超管 true 公司管理员false
            };

            return Success(data);
        }

        /// <summary>
        /// 创建公司管理员用户
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> SubAddInfo(CompanySubAdd RequestData)
        {
            //检测账号名是否存在
            var res = await _dbContext.Users.Where(m => m.UserName == RequestData.UserName).FirstOrDefaultAsync();
            if (res != null)
            {
                return Error(null, "用户名已经存在");
            }

            var u = userManager.GetUserAsync(User).Result;
            //当前公司信息
            Company CompanyInfo = _CompanyService.GetInfo(u.CompanyId);
            int num = _UserService.GetUserNum(u.Id, u.CompanyId, u.OemId);
            var openUserNum = CompanyInfo.OpenUserNum - num;
            if (openUserNum < 1 && CompanyInfo.IsOpenUser == Company.IsOpenUsers.DISABLE)
            {
                return Error(message: "无法开通更多用户");
            }

            //权限模版信息
            RuleTemplateService RuleTemplateService = new(_dbContext);
            var RuleTemplates = RuleTemplateService.GetRuleTemplateInfo(RequestData.RuleId, u.CompanyId, u.OemId);
            //选择有效期转换10位时间戳
            long validity = Helper.GetTimeStamp(RequestData.Validity);

            using (var scope = _dbContext.Database.BeginTransaction()) //创建事务
            {
                try
                {
                    // TODO:这个地方实现有问题，当事务报错还是会提交错误之前的事务。用户判断应该用逻辑掌控，只有返回成功了，才继续往下执行。
                    // 错误触发trigger：前台输入中文用户名提交
                    //添加有效期信息
                    ValidityService ValidityService = new(_dbContext);
                    int ValidityId = await ValidityService.InitValidity(validity);
                    //初始化公司信息
                    int CompanyId = await _CompanyService.InitCompanyConfig(RequestData, CompanyInfo, ValidityId, validity);

                    //添加公司管理员账号
                    User NewUsermodel = _UserService.InitCompanyUser(RequestData, u, CompanyId);
                    //int UserId =  _UserService.InitCompanyUser(RequestData, u, CompanyId);

                    var AddUserRet = await userManager.CreateAsync(NewUsermodel, RequestData.Password);
                    var AddRoleRet = await userManager.AddToRoleAsync(NewUsermodel, "company");

                    ////初始化权限模版 复制权限模板
                    RuleTemplate NewRuleTemplate = await RuleTemplateService.InitRuleTemplateAsync(RuleTemplates, CompanyId, RequestData.OemId);

                    var AddAuthRet = await userManager.AddClaimsAsync(NewUsermodel, NewRuleTemplate.GetClaims(RequestData.OemId));

                    //创建用户信息日志
                    var AddLogRet = _UserService.AddUserLog(NewUsermodel.Id, "创建用户", u);
                    //初始化用户组
                    UserGroupService UserGroupService = new(_dbContext);
                    await UserGroupService.InitUserGroup(CompanyId, RequestData.OemId);

                    scope.Commit(); //重点，事务的提交
                }
                catch (Exception e)
                {
                    //scope.Rollback();
                    scope.Rollback();
                    return Error(e.Message);
                }
            }
            return Success();
        }


        /// <summary>
        /// 获取公司管理员编辑需要信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ResultStruct GetEditInfo(GetDataId RequestData)
        {
            var u = userManager.GetUserAsync(User).Result;
            //权限组
            RuleTemplateService RuleTemplateService = new(_dbContext);
            var RuleTemplates = RuleTemplateService.GetAllRuleTemplate(u.CompanyId, u.OemId);
            //用户可编辑信息
            var Info = _UserService.GetEditCompanyUser(RequestData.Id);

            var data = new
            {
                RuleTemplates = RuleTemplates,
                Info = Info
            };

            return Success(data);
        }


        /// <summary>
        /// 更新公司管理员信息
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ResultStruct SubEditInfo(CompanySubEdit RequestData)
        {
            User UserInfo = _UserService.GetInfo(RequestData.Id);
            if (UserInfo == null) return Error(message: "无权操作");

            var u = userManager.GetUserAsync(User).Result;

            using (var scope = new CommittableTransaction()) //创建事务
            {
                try
                {
                    //更新用户信息
                    _UserService.EditCompanyUser(RequestData, UserInfo);

                    //更新公司  RuleId State
                    if (UserInfo.RuleId != RequestData.RuleId || UserInfo.State != RequestData.State)
                    {
                        var dic = new Dictionary<string, object>
                        {
                            ["State"] = RequestData.State,
                            ["RuleId"] = RequestData.RuleId
                        };
                        _CompanyService.UpdateComapny(dic, UserInfo.CompanyId);
                    }

                    //状态  启用->禁用  禁用当前公司下全部用户
                    if (UserInfo.State != RequestData.State && RequestData.State == States.DISABLE)
                    {
                        _UserService.EditorUserState(UserInfo.CompanyId, RequestData.State);
                        //公司下全部用户 掉线
                    }

                    //增加更新用户信息日志
                    _UserService.AddUserLog(UserInfo.Id, "修改用户信息", u);


                    scope.Commit(); //重点，事务的提交
                }
                catch (Exception e)
                {
                    //scope.Rollback();
                    scope.Dispose();
                    return Error(e.Message);
                }
            }

            return Success();
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> ResetPasswordAsync(GetDataId RequestData)
        {
            User UserInfo = _UserService.GetInfo(RequestData.Id);
            var u = userManager.GetUserAsync(User).Result;

            var token = await userManager.GeneratePasswordResetTokenAsync(UserInfo);

            var ret = await userManager.ResetPasswordAsync(UserInfo, token, "123456");

            //创建用户信息日志
            var AddLogRet = _UserService.AddUserLog(RequestData.Id, "创建用户", u);

            return Success();
        }

        /// <summary>
        /// 获取用户日志
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<ResultStruct> GetUserLogList([FromQuery] int Id)
        {
            var data = await _UserService.GetUserLogPaginate(Id, Request);
            return Success(data);
        }

        /// <summary>
        /// 公司配置信息
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public ResultStruct GetCompanyConfigInfo(GetDataId RequestData)
        {
            var u = userManager.GetUserAsync(User).Result;

            //公司配置信息
            Company CompanyInfo = _CompanyService.GetInfo(RequestData.Id);

            var Info = new
            {
                Id = CompanyInfo.Id,
                Name = CompanyInfo.Name,
                IsOpenUser = CompanyInfo.IsOpenUser,
                OpenUserNum = CompanyInfo.OpenUserNum,
                Validity = Helper.TimeStampToDate(CompanyInfo.ShowValidity),
                OemId = CompanyInfo.OemId,
                NumberOfPoints = CompanyInfo.NumberOfPoints,
            };

            //有效期最大日期
            string LimitValidity = DateTime.Today.AddYears(10).ToString("yyyy-MM-dd");
            Company.IsOpenUsers IsOpenUser = Company.IsOpenUsers.ENABLE;
            int OpenUserNum = 0;

            if (u.CompanyId != 1)
            {
                Company CurrentCompanyInfo = _CompanyService.GetInfo(u.CompanyId);
                IsOpenUser = CurrentCompanyInfo.IsOpenUser;
                OpenUserNum = CurrentCompanyInfo.OpenUserNum;

                ValidityService ValidityService = new(_dbContext);
                Validity ValidityInfo = ValidityService.GetMaxValidity(CurrentCompanyInfo.ValidityIds);
                LimitValidity = Helper.TimeStampToDate(ValidityInfo.validity);
            }

            OemService OemService = new(_dbContext);
            var Oems = OemService.GetOwnOems(u);
            //已使用的数量
            int num = _UserService.GetUserNum(u.Id, u.CompanyId, u.OemId);
            //当前公司已开通的用户数量
            var SubCompanyAdmin = _dbContext.Users.Where(m => m.CompanyId == RequestData.Id && m.Type == UserModel.Types.CompanyAdmin).FirstOrDefault();
            
            if(SubCompanyAdmin == null)
            {
                return Error("公司账号不存在");
            }

            int SubCompanyNum = _UserService.GetUserNum(SubCompanyAdmin.Id, RequestData.Id, SubCompanyAdmin.OemId);
            var data = new
            {
                LimitValidity = LimitValidity,
                IsOpenUser = IsOpenUser,
                OpenUserNum = OpenUserNum - num,
                MinOpenUserNum = SubCompanyNum,
                Oems = Oems,
                Info = Info
            };

            return Success(data);
        }

        /// <summary>
        /// 提交公司配置信息
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ResultStruct SubConfigInfo(CompanyConfigSub requestData)
        {
            var u = userManager.GetUserAsync(User).Result;

            //公司配置信息
            Company companyInfo = _CompanyService.GetInfo(requestData.Id);

            if (companyInfo == null) return Error(message: "无权操作");

            var companyAdmin = _dbContext.Users.Where(u => u.CompanyId == companyInfo.Id)
                .Where(u => u.Type == UserModel.Types.CompanyAdmin)
                .Select(u => new {Id = u.Id})
                .FirstOrDefault();
            if (companyAdmin == null)
            {
                return Error(message: "无效公司");
            }

            //当前公司已开通的用户数量
            var SubCompanyAdmin = _dbContext.Users.FirstOrDefault(m => m.CompanyId == requestData.Id && m.Type == UserModel.Types.CompanyAdmin);

            if (SubCompanyAdmin == null)
            {
                return Error("公司账号不存在");
            }

            int SubCompanyNum = _UserService.GetUserNum(SubCompanyAdmin.Id, requestData.Id, SubCompanyAdmin.OemId);

            if(requestData.IsOpenUser == Company.IsOpenUsers.DISABLE && requestData.OpenUserNum < SubCompanyNum)
            {
                return Error(new() { },$"该公司已开通用户[{SubCompanyNum}]个");
            }

            //已使用的数量
            int num = _UserService.GetUserNum(u.Id, u.CompanyId, u.OemId);

            Company CurrentCompanyInfo = _CompanyService.GetInfo(u.CompanyId);
            int surplusNum = CurrentCompanyInfo.OpenUserNum - num;

            if((u.CompanyId != 1 && u.CompanyId != 3) && requestData.OpenUserNum > surplusNum && CurrentCompanyInfo.IsOpenUser == Company.IsOpenUsers.DISABLE)
            {
                return Error(new() { }, "数量超出限制");
            }


            var dic = new Dictionary<string, object>
            {
                ["IsOpenUser"] = requestData.IsOpenUser,
                ["Name"] = requestData.Name,
                ["OpenUserNum"] = requestData.OpenUserNum,
                ["ShowOemId"] = requestData.OemId,
            };
            if (requestData.NumberOfPoints != 0) 
            {
                // FIXME ef没有increment,需要使用自增减，目前使用强制覆盖会出现问题
                dic["NumberOfPoints"] =companyInfo.NumberOfPoints + requestData.NumberOfPoints;
            }
            long validity = Helper.GetTimeStamp(requestData.Validity);


            using var scope = new CommittableTransaction();
            try
            {
                if (validity != companyInfo.ShowValidity)
                {
                    dic["ShowValidity"] = validity;
                    //更新有效期信息
                    ValidityService ValidityService = new(_dbContext);
                    ValidityService.UpdateValidity(companyInfo.ShowValidityId, validity);
                }

                _CompanyService.UpdateComapny(dic, requestData.Id);
                _UserService.AddUserLog(companyAdmin.Id, "更新用户", u);
                if (requestData.NumberOfPoints != 0) 
                {
                    _UserService.AddUserLog(companyAdmin.Id, $"更新用户积分【{requestData.NumberOfPoints}】", u);
                }

                scope.Commit();
            }
            catch (Exception e)
            {
                scope.Rollback();
                return Error(e.Message);
            }

            return Success();
        }

        /// <summary>
        /// 系统管理 -公司配置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ResultStruct GetSysCompanyConfig()
        {
            var u = userManager.GetUserAsync(User).Result;

            //公司配置信息
            Company CompanyInfo = _CompanyService.GetInfo(u.CompanyId);

            var data = new
            {
                Name = CompanyInfo.Name,
                Validity = Helper.TimeStampToDate(CompanyInfo.ShowValidity),
                IsOpenUser = CompanyInfo.IsOpenUser,
                OpenUserNum = CompanyInfo.OpenUserNum,
                IsUnlimitedPoints = CompanyInfo.IsUnlimitedPoints,
                NumberOfPoints = CompanyInfo.NumberOfPoints,
                IsRepetitionAllowed = CompanyInfo.IsRepetitionAllowed,
                AutoWatersDay = CompanyInfo.AutoWatersDay,
            };

            return Success(data);
        }

        /// <summary>
        /// 系统管理 -公司配置信息提交
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public ResultStruct SubSysCompanyConfig(SysCompanyConfig RequestData)
        {
            var u = userManager.GetUserAsync(User).Result;
            var dic = new Dictionary<string, object>
            {
                ["Name"] = RequestData.Name,
                ["IsRepetitionAllowed"] = RequestData.IsRepetitionAllowed,
                ["AutoWatersDay"] = RequestData.AutoWatersDay,
            };
            _CompanyService.UpdateComapny(dic, u.CompanyId);
            return Success();
        }


        /// <summary>
        /// 个人中心展示数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> GetUserCenterInfo()
        {
            var userInfo = await userManager.GetUserAsync(User);

            var companyInfo = await _dbContext.Company.Where(m => m.Id == userInfo.CompanyId).FirstOrDefaultAsync();


            var data = new
            {
                Username = userInfo.UserName,
                Settings = userInfo.SettingsObj,
                Name = userInfo.TrueName,
                Avatar = userInfo.Avatar,
                Created = userInfo.CreatedAt,
                Validity = userInfo.Type == UserModel.Types.Employee && userInfo.Validity is not null ? userInfo.Validity!.Value.ToString("yyyy-MM-dd") : Helper.TimeStampToDate(companyInfo.ShowValidity)
            };

            return Success(data);
        }

        /// <summary>
        /// 修改个人中心姓名
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubUserCenterInfo(SysCompanyConfig RequestData)
        {
            var u = await userManager.GetUserAsync(User);
            var dic = new Dictionary<string, object>
            {
                ["TrueName"] = RequestData.Name,
                ["Settings"] = JsonConvert.SerializeObject(RequestData.Settings),
            };
            _UserService.EditUserById(dic, u.Id);
            return Success();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubUserCenterPassword(UserCenterPassword RequestData)
        {
            User UserInfo = userManager.GetUserAsync(User).Result;

            var ret = await userManager.ChangePasswordAsync(UserInfo, RequestData.OriginalPassword, RequestData.Password);

            return ret.Succeeded ? Success() : Error(null, ret.Errors.First().Description);
        }

        /// <summary>
        /// 更新用户头像
        /// </summary>
        /// <param name="FormFile"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public async Task<ResultStruct> UploadAvatarImg([FromForm] IFormCollection FormFile, [FromServices] UploadService _UploadService)
        {
            //FormFileCollection FileCollection = (FormFileCollection)FormFile.Files;

            var FileFolder = Path.Combine("", "temporary/avatar/");
            UploadService.ResultObject ret = await _UploadService.UploadSingleImg(FileFolder, FormFile);
            if (!ret.State)
            {
                return Error(ret.Data);
            }
            //更新用户头像信息
            var u = userManager.GetUserAsync(User).Result;
            var dic = new Dictionary<string, object>
            {
                ["Avatar"] = ret.Data
            };
            _UserService.EditUserById(dic, u.Id);

            return Success(ret.Data);

        }
    }
}